//
//  HELCourseVedioVC.m
//  HandheldELearn
//
//  Created by wsj2015 on 16/8/2.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "HELCourseVedioVC.h"

#import "HELHomeCell.h"
#import "HMSegmentedControl.h"
#import "NinaSelectionView.h"
#import "HELCourseItemCell.h"
#import "JCAlertView.h"
#import "HELVedioListModel.h"
#import "CWQPrepareForVideoVC.h"
@interface HELCourseVedioVC ()<UICollectionViewDelegate,UICollectionViewDataSource,NinaSelectionDelegate>


@property (nonatomic,  strong) UICollectionView *collectView;
@property (nonatomic,  strong) NinaSelectionView *ninaSelectionView;
@property (nonatomic,  strong) HMSegmentedControl *segment;
@property (nonatomic,  strong) UIButton *moreBtn;


//0 院内   1公开
@property (nonatomic,  assign) NSInteger currentIndex;


@property (nonatomic,  strong) NSArray *typeArray;

@property (nonatomic, strong)  NSMutableArray *hospitalInArr;

@property (nonatomic,  strong) NSMutableArray *pubilcArr;


@end

@implementation HELCourseVedioVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
   
    self.hospitalInArr = [NSMutableArray array];
    self.pubilcArr = [NSMutableArray array];

    
}

#pragma mark - LazyLoad
- (NinaSelectionView *)ninaSelectionView {
    if (!_ninaSelectionView) {
        _ninaSelectionView = [[NinaSelectionView alloc] initWithTitles:self.typeArray PopDirection:NinaPopFromAboveToTop];
        _ninaSelectionView.ninaSelectionDelegate = self;
        _ninaSelectionView.defaultSelected = 1;
        _ninaSelectionView.shadowEffect = YES;
        _ninaSelectionView.shadowAlpha = 0.5;
        defineWeakSelf;
       
        _ninaSelectionView.ninaDidDismiss = ^(){
            [UIView animateWithDuration:.35f animations:^{
                 weakSelf.moreBtn.transform = CGAffineTransformIdentity;
            }];
           
        };
    }
    return _ninaSelectionView;
}

- (void)configUI{
    self.currentIndex = 0;
    
    self.typeArray = @[@"院内",@"公开"];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.collectView.frame = CGRectMake(0, 39, kScreenWidth, kScreenHeight -64-39);
    [self.view addSubview:self.collectView];
    
    [self.view addSubview:self.ninaSelectionView];
    HMSegmentedControl *segmentedControl3 = [[HMSegmentedControl alloc] initWithSectionTitles:self.typeArray];
    [segmentedControl3 setFrame:CGRectMake(0, 0, kScreenWidth -44, 39)];
    defineWeakSelf;
  
    

    [segmentedControl3 setIndexChangeBlock:^(NSInteger index) {
        weakSelf.currentIndex = index;
       
         [weakSelf reloadCollectionView];
        if (weakSelf.currentIndex ==0) {
            if (weakSelf.hospitalInArr.count <=0) {
                [weakSelf requestVedioListData:YES];
                
            }else{
               
            }
        }else{
            if (weakSelf.pubilcArr.count <=0) {
                [weakSelf requestVedioListData:YES];
            }else{
                
            }
        
        }
       
    
        
    }];
    segmentedControl3.selectionIndicatorHeight = 2.0f;
    segmentedControl3.backgroundColor = HexRGB_WSJ(221, 221, 221);
    segmentedControl3.titleTextAttributes = @{NSForegroundColorAttributeName : [UIColor blackColor],NSFontAttributeName:[UIFont systemFontOfSize:14]};
     segmentedControl3.selectedTitleTextAttributes = @{NSForegroundColorAttributeName :[UIColor orangeColor],NSFontAttributeName:[UIFont systemFontOfSize:14]};
    segmentedControl3.selectionIndicatorColor = [UIColor orangeColor];
    segmentedControl3.selectionStyle = HMSegmentedControlSelectionStyleFullWidthStripe;
    segmentedControl3.selectedSegmentIndex = 0;
    segmentedControl3.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
    segmentedControl3.segmentWidthStyle = HMSegmentedControlSegmentWidthStyleFixed;
    segmentedControl3.shouldAnimateUserSelection = YES;
    self.segment = segmentedControl3;
    segmentedControl3.segmentEdgeInset = UIEdgeInsetsMake(0, 5, 0, 10);
    [self.view addSubview:segmentedControl3];

    UIButton *btn =[UIButton buttonWithType:UIButtonTypeSystem];
//    [btn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [btn setBackgroundColor:HexRGB_WSJ(221, 221, 221)];
    btn.frame  =CGRectMake(CGRectGetMaxX(segmentedControl3.frame), 0, 44, 39);
    [btn setTintColor:[UIColor whiteColor]];
//    [btn setTitle:@"🔽" forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"indecator_down"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(popMoreMenu) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    self.moreBtn = btn;
    
   
    [self.collectView wsj_HeaderRefreshBlock:^{
        [weakSelf requestVedioListData:YES];
    }];
    [self.collectView addLegendFooterWithRefreshingBlock:^{
          [weakSelf requestVedioListData:NO];
    }];
    
    [self.collectView.header beginRefreshing];
    
    
   
}


#pragma mark -切换动画
- (void)reloadCollectionView{
//    presentedView.transform = CGAffineTransformMakeScale(1.0, 0.0)
//    //锚点设置
//    presentedView.layer.anchorPoint = CGPointMake(0.5, 0)
//    self.collectView.layer.anchorPoint = CGPointMake(.5, 0);
//   __block  CGRect frame = self.collectView.frame;
//   frame.size.height =64;
//    defineWeakSelf;
//   [UIView animateWithDuration:.35f animations:^{
//       weakSelf.collectView.frame = frame;
//   } completion:^(BOOL finished) {
//       [weakSelf.collectView reloadData];
//       frame.size.height = kScreenHeight -64-39;
//       [UIView animateWithDuration:.35f animations:^{
//        weakSelf.collectView.frame = frame;
//       } completion:^(BOOL finished) {
////            self.collectView.layer.anchorPoint = CGPointMake(0.5, 0.5);
//       }];
//   }];
    [self.collectView performBatchUpdates:^{
        [self.collectView reloadSections:[NSIndexSet indexSetWithIndex:0]];
    } completion:nil];
}

#pragma mark -请求数据
- (void)requestVedioListData:(BOOL)isRecover{
//    currentPage    pageSize
    NSString *hospitalId = [HELAppManager userInfo].hospitalId;
    if (!hospitalId) {
        [JCAlertView showOneButtonWithTitle:@"提示" Message:@"该用户不属于任何医院..." ButtonType:JCAlertViewButtonTypeWarn ButtonTitle:@"确定" Click:nil];
        return;
    }
    static NSInteger hospitalInCurrentPage =1;
    static NSInteger publicCurrentPage =1;
    NSMutableDictionary *params =[NSMutableDictionary dictionary];

    //院内
    if (self.currentIndex ==0) {
        if (isRecover) {
            hospitalInCurrentPage =1;
        }else{
            hospitalInCurrentPage ++;
        }
          params[@"currentPage"] = @(hospitalInCurrentPage);
    }else{
        if (isRecover) {
            publicCurrentPage =1;
        }else{
            publicCurrentPage ++;
        }
        hospitalId = [NSString stringWithFormat:@"%@",@(-1)];
        params[@"currentPage"] = @(publicCurrentPage);
    }

    params[@"pageSize"] = @(12);
    params[@"hospitalId"] = hospitalId;
    weakSelf_define;
    [[HELNetworkManager sharedMg] GET:kVedioList parameters:params success:^(NSDictionary *responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            if ([responseObject[@"rows"] isKindOfClass:[NSArray class]]) {
                    //院内
                    if (self.currentIndex ==0) {
                        
                        if (isRecover) {
                            [weakSelf.hospitalInArr removeAllObjects];
                        }
                        
                        [weakSelf.hospitalInArr addObjectsFromArray:[HELVedioListModel mj_objectArrayWithKeyValuesArray:responseObject[@"rows"]]];
                        //公开
                    }else{
                        if (isRecover) {
                            [weakSelf.pubilcArr removeAllObjects];
                        }
                        
                        [weakSelf.pubilcArr addObjectsFromArray:[HELVedioListModel mj_objectArrayWithKeyValuesArray:responseObject[@"rows"]]];
                       
                    }
                
                
                
                }
             
        }
        [weakSelf.collectView.footer endRefreshing];
        [weakSelf.collectView.header endRefreshing];
        [weakSelf.collectView reloadData];
        
        
    } failure:^(NSString *err) {
        [weakSelf.collectView.footer endRefreshing];
        [weakSelf.collectView.header endRefreshing];
    }];
    
}

#pragma mark -跟多分类菜单
- (void)popMoreMenu{
    
    self.moreBtn.transform = CGAffineTransformRotate(self.moreBtn.transform, M_PI);
    self.ninaSelectionView.defaultSelected = self.currentIndex+1;
    [self.ninaSelectionView showOrDismissNinaViewWithDuration:0.5 usingNinaSpringWithDamping:0.8 initialNinaSpringVelocity:0.3];

}
#pragma mark - NinaSelectionDelegate
- (void)selectNinaAction:(UIButton *)button {
    NSLog(@"Choose %li button",(long)button.tag);
    self.segment.selectedSegmentIndex = button.tag-1;
    self.currentIndex = button.tag-1;
    [self.ninaSelectionView showOrDismissNinaViewWithDuration:0.3];
    if (self.currentIndex ==0) {
        if (self.hospitalInArr.count <=0) {
            [self requestVedioListData:YES];
            
        }else{
            [self reloadCollectionView];
        }
    }else{
        if (self.pubilcArr.count <=0) {
            [self requestVedioListData:YES];
        }else{
            [self reloadCollectionView];
        }
        
    }

   
    
    
}


- (UICollectionView *)collectView{
    if (!_collectView) {
        
        UICollectionViewFlowLayout *layout =[[UICollectionViewFlowLayout alloc]init];
        
        
        CGFloat space = 12;
//        layout.itemSize = CGSizeMake(kScreenWidth -10, 100);
        layout.sectionInset =UIEdgeInsetsMake(10, space, 10, space );
        layout.minimumInteritemSpacing = 4;
        layout.minimumLineSpacing = 6;
        CGRect frame =CGRectMake(0, 0, kScreenWidth, kScreenHeight -64);
        _collectView =[[UICollectionView alloc]initWithFrame:frame collectionViewLayout:layout];
        _collectView.delegate = self;
        _collectView.dataSource = self;
        _collectView.showsVerticalScrollIndicator = NO;
        _collectView.alwaysBounceVertical =YES;
        _collectView.backgroundColor = kAppBg;
        [_collectView registerNib:[UINib nibWithNibName:@"HELCourseItemCell" bundle:nil] forCellWithReuseIdentifier:@"HELCourseItemCell"];
        //
        
        
    }
    return _collectView;
    
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    
    if (self.currentIndex == 0) {
        return self.hospitalInArr.count;
    }else{
        return self.pubilcArr.count;
    }
    
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HELCourseItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HELCourseItemCell" forIndexPath:indexPath];
    
    //院内
    HELVedioListModel *model;
    if (self.currentIndex == 0) {
        model= self.hospitalInArr[indexPath.row];
    }else{
        model= self.pubilcArr[indexPath.row];
    
    }
    cell.model = model;
    return cell;

}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{

    
    
    
        //适配屏幕
        CGFloat w = (kScreenWidth -12 *3)/2;
        CGFloat h = 148 * kScreenFactor;
        return CGSizeMake(w, h);
    
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    //院内
    HELVedioListModel *model;
    if (self.currentIndex == 0) {
        model= self.hospitalInArr[indexPath.row];
    }else{
        model= self.pubilcArr[indexPath.row];
        
    }
    CWQPrepareForVideoVC *videoVC = [[CWQPrepareForVideoVC alloc] initWithModel:model];
    HELNavigationContrller *nav = [[HELNavigationContrller alloc] initWithRootViewController:videoVC];
    [self presentViewController:nav animated:YES completion:nil];

}

@end
